﻿<?php
class User extends MY_Controller
{
	var $curl = 'user';
	var $name = '';
	var $search = '';
	var $per_page = 0;
	var $language;
	var $submenu = "_menu";
	var $id_user = '';
    //!!! changes according to server
    
    var $db_error = "Prolem with your data base request. Check the parameters.";

	function __construct()
	{
		parent::__construct();

		$this->load->model(array('/public/user_model', '/public/friends_model',
                                 '/public/geo_country_model', '/public/geo_state_model', '/public/geo_city_model',
                                '/public/captcha_model', '/public/contact_us_model',
								 '/public/state_model', '/public/referral_model',
                                 '/public/bids_model', '/public/inbox_model'));

		$this->data['Title'] = T_('Users');

		$this->name = T_('Users');
	}

	function register() {

        session_start();

        $friendsCode = $this->input->get('fr_code');
        $coderef    = $this->input->get('ver_code');
        $userType   = $this->input->get('ur_type');

        $this->data['friendCode'] = $friendsCode;
        $this->data['buyer']  =($userType=='Seller'?FALSE:TRUE);
        $this->data['seller'] = !($this->data['buyer']);

        if(!empty($coderef)){
            $isok = $this->user_model->verifyUserEmail($coderef);
            $viewred = '/user/'.($isok===true?'final_registration':'email_verification');
            $this->view = $viewred;
            
        } else {
        
        $this->validation->set_fields($this->user_model->fields);
        $this->data['hiddenInfo'] = $this->input->get_post('user_id_acl_roles');
        
        if ($this->input->post('continue')){ //first stage
            $this->data['Title'] = T_('Register');
            $this->data['friendCode'] = $this->input->get_post('friendCode');
            $this->view ='/user/register';
        
        } else if($this->input->post('register')){//second stage
            $this->register_stage2();
        } else if($this->input->post('joinnow')){//third stage
            $this->register_stage3();
        } else if($this->input->post('resend')){

               email_verification();

        } else if($this->input->post('final_sign_in')){// fifth stage - restoring info in db

            redirect('/user/login');
        }else{
            $this->view = '/user/choice';
        }
        }
         $this->renderLayout();
	}
 
    function register_stage2(){
               $rules = array('first_name', 'last_name', 'email', 'email_confirm', 'password', 'password_confirm', 'payment_method', 'captcha_code');
               $this->validation->set_rules($this->user_model->getRules($rules));
               $this->validation->set_message('__captcha', T_('Incorrect verification code.'));
               $this->data['Title'] = T_('Register');
               if ($this->validation->run() === TRUE){
                 
                    $user_first_name    = $this->validation->first_name;
                    $user_last_name     = $this->validation->last_name;
                    $user_email         = $this->validation->email;
                    $user_password      = $this->validation->password;
                        $paymentMethod      = $this->config->item('paymentMethod');
                    $user_payment_method= $paymentMethod[$this->validation->payment_method];
                    

                    $user_status        = USER_STATUS_BLOCKED;

                    $arr['user_id_acl_roles'] = $_POST['user_id_acl_roles'];
                    $arr['user_first_name'] = $user_first_name;
                    $arr['user_last_name'] = $user_last_name;
                    $arr['user_email'] = $user_email;
                    $arr['user_password'] = $user_password;

                    $arr['user_payment_method'] = $user_payment_method;

                    $this->data['hiddenInfo'] = $arr;
                    $this->data['friendCode'] = $_POST['friendCode'];
                    $this->data['Title'] = T_('You do not pay a fee to Register!');
                    $this->data['Title1'] = T_('Provide Your Payment Info');

                    $this->view ='/user/payment_info';

               }else{
                    $this->view ='/user/register';
               }
    }
    function register_stage3(){
            $country = $_POST['country_ID'];
            $rules = array('address','city','country_ID','zip_code','card_type','card_number','exp_month', 'exp_year','security_code');
            if($country == "840"){
                $rules[]='state_ID';
            }else if($country!=="0"){
                $rules[]='province';
            }
            
            $this->validation->set_rules($this->user_model->getRules($rules));

            $arr['user_id_acl_roles']   = $_POST['user_id_acl_roles']+2;
            $arr['user_first_name']     = $_POST['user_first_name'];
            $arr['user_last_name']      = $_POST['user_last_name'];
            $arr['user_email']          = $_POST['user_email'];
            $arr['user_password']       = $_POST['user_password'];
            $arr['user_payment_method'] = $_POST['user_payment_method'];
            $fr_code                    = $_POST['friendCode'];
            
			if ($this->validation->run() === TRUE)
			{
                $arr['user_country_ID'] = $this->validation->country_ID;
                
				if($arr['user_country_ID']=='840'){
                    $states = $this->geo_state_model->getSelectOptions($arr['user_country_ID']);
                    $arr['user_state']  = $states[$this->validation->state_ID];

                }else{
                    $arr['user_state']  = $this->validation->province;
                }
                $countries               = $this->geo_country_model->getSelectOptions();
                $userCard                = $this->config->item('cardTypeitem');
                $userMonth               = $this->config->item('expMonthitem');
                $userYear                = $this->config->item('expYearitem');
                
                $arr['user_address']    = $this->validation->address;
                $arr['user_city']       = $this->validation->city;
                $arr['user_country']    = $countries[$arr['user_country_ID']];
                $arr['user_zip_code']   = $this->validation->zip_code;
                $arr['user_card_type']  = $userCard[$this->validation->card_type];
                $arr['user_card_number']= $this->validation->card_number;
                $arr['user_exp_month']  = $userMonth[$this->validation->exp_month];
                $arr['user_exp_year']   = $userYear[$this->validation->exp_year];
                $arr['user_security_code'] = $this->validation->security_code;
                $arr['user_verification_code'] = generatecode();

                $this->user_model->insert($arr);

                $data_user['user_first_name']   = $arr['user_first_name'];
                $data_user['user_last_name']    = $arr['user_last_name'];
                $link = $this->config->item('site_url') . $this->config->item('base_url') .'user/register/?ver_code='.$arr['user_verification_code'];
                $data_user['activation_link']   = '<a href="'.$link.'">'.$link.'</a>';
                $data_user['activation_code']   = $arr['user_verification_code'];
                $data_user['email']             = $arr['user_email'];

                if($arr['user_id_acl_roles']=="3"){
                    $data_user['email_name'] = EMAIL_REGISTER_BUYER;
                }else if($arr['user_id_acl_roles']=="4"){
                    $data_user['email_name'] = EMAIL_REGISTER_SELLER;
                }else{
                    $data_user['email_name'] = EMAIL_REGISTER_BOTH;
                }

                $result = sendEmail($data_user);

                if(!empty($fr_code)){
                    $this->friends_model->verifyFriend($fr_code);//need some additional check?
                }
                $this->data['Title'] = T_('E-Mail Verification');
                $this->view          = "/user/email_verification";

            } else {
                $this->view = "/user/payment_info";
            }

            $this->data['hiddenInfo'] = $arr;
    }
    function email_verification() {
	    if($this->input->post('verification')){//fourth stage
	            
                $rules = array('verify_input');
                $this->validation->set_rules($this->user_model->getRules($rules));

                if ($this->validation->run() === TRUE){
                    $coderef = $this->validation->verify_input;
                    $isok = $this->user_model->verifyUserEmail($coderef);
                    //$viewred = '/user/'.(($isok===true)?'final_registration':'email_verification');
                    if($isok===true){
                        //k3pvjl234ogc8uq3e
                        $this->view = '/user/final_registration';
                    }else{
                        $this->data['Title'] = 'Thank you for joing HNBooks';
                        $this->view = '/user/email_verification';
                    }
                    
                }
    	}
    	$this->data['Title'] = T_('E-Mail Verification');

    	$this->renderLayout();
    }
	function login($forgot_completed = null)
	{
		if (isset($_POST['enter']))
		{
			if ($user = $this->user_model->getByLoginPassword($this->input->post('user_email'), $this->input->post('user_password')))
			{
				//echo $user['user_status'];
				if($user['user_status'] == 2) {
					$this->data['login_error'] = '<p class="msg error">'.T_('Your account has not activated. You can do this by clicking on next link').'&nbsp;'.
													anchor('user/email_verification', T_('E-Mail Verification'), 'id="email_verification"').'</p>';
				}else {
					if ($user['user_status'] != 3)
					{
						$this->auth->cookieIndex = 'key_users';
						$this->auth->login($user);
	
						redirect('/');
					}
					else
					{
						$this->data['login_error'] = '<p class="msg error">'.T_('Your account has been locked.').'</p>';
						//$this->log->writeMessage('error', T_('Your account has been locked.'));
					}
				}
			}
			else
			{
				$this->data['login_error'] = T_('<p class="msg error">'.T_("Incorrect login or password").'</p>');
				//$this->log->writeMessage('error', T_('Invalid login or password.'));
			}
		}

		$this->data['forgot_completed'] = $forgot_completed;
		$this->data['forgot_error'] = '';
		//$this->layout 	= 'login';
		//$this->view 	= 'admins/login';
		$this->data['hide_menu'] = true;
		$this->data['Title'] = 'Sign In';
		$this->renderLayout();
	}

	function password_forgot()
	{
		if (count($_POST))
		{
			$this->user_model->rules =	array(
											'forgot_user_login' => "trim|required|valid_email|max_length[64]"
										);
			$rules = array('forgot_user_login');
			$this->validation->set_rules($this->user_model->getRules($rules));

			if ($this->validation->run() === TRUE)
			{
				if ($user=$this->user_model->getByLogin($this->input->post('forgot_user_login')))
				{
					if ($user['status'] == USER_STATUS_ACTIVE)
					{
						$new_password = humanPassword(6);
						$subject = "New password";
	     				$item['id'] = $user['id'];
	    				$item['activation_code'] = $this->user_model->__cryptPassword($new_password);
	    				$message = "Hello ".$user['fullname'].".<br />
								    Your new password: $new_password
	     						    <a target='_blank' href='".$this->config->item('site_url') . $this->config->item('base_url')."user/reset_password/".$item['activation_code']."'>".$this->config->item('site_url') . $this->config->item('base_url')."user/reset_password/".$item['activation_code']."</a>.\n\r
	    							You may change the password after authorisation.<br />

	    							Sincerely,<br />
									Website Administration.";
						//$item['date_modified'] = date('Y-m-d H:i:s');
						$sql = 'UPDATE '.$this->user_model->table.' SET activation_code='.$this->db->escape($item['activation_code']).' WHERE id='.$item['id'];

						$this->db->query($sql);

						$this->load->library('email');
						$config['mailtype'] = 'html';
						$config['protocol'] = 'mail';
						$config['charset'] = 'utf-8';
						$config['newline'] = '\r\n';

						$this->email->initialize($config);
						$this->email->from($this->config->item('site_email'), EMAIL_FROM_NAME);
						$this->email->to($user['email']);
						$this->email->subject($subject);
						$this->email->message($message);
						$this->email->send();

						redirect($this->curl . '/login/forgot_completed');
					}
					else
					{
						$this->data['forgot_error'] = $this->validation->_error_prefix . T_('Your account has been locked.') . $this->validation->_error_suffix;
					}
				}
				else if ($user = $this->company_model->getByLogin($this->input->post('forgot_user_login')))
				{
					if ($user['status'] == USER_STATUS_ACTIVE)
					{
						$new_password = humanPassword(6);
						$subject = "New password";
	     				$item['id'] = $user['id'];
	    				$item['activation_code'] = $this->company_model->__cryptPassword($new_password);
	    				$message = "Hello ".$user['fullname'].".<br />
								    Your new password: $new_password
	     						    <a target='_blank' href='".$this->config->item('site_url') . $this->config->item('base_url')."user/reset_password/".$item['activation_code']."'>".$this->config->item('site_url') . $this->config->item('base_url')."user/reset_password/".$item['activation_code']."</a>.\n\r
	    							You may change the password after authorisation.<br />

	    							Sincerely,<br />
									Website Administration.";
						//$item['date_modified'] = date('Y-m-d H:i:s');
						$sql = 'UPDATE '.$this->company_model->table.' SET activation_code='.$this->db->escape($item['activation_code']).' WHERE id='.$item['id'];

						$this->db->query($sql);

						$this->load->library('email');
						$config['mailtype'] = 'html';
						$config['protocol'] = 'mail';
						$config['charset'] = 'utf-8';
						$config['newline'] = '\r\n';

						$this->email->initialize($config);
						$this->email->from($this->config->item('site_email'), EMAIL_FROM_NAME);
						$this->email->to($user['email']);
						$this->email->subject($subject);
						$this->email->message($message);
						$this->email->send();

						redirect($this->curl . '/login/forgot_completed');
					}
					else
					{
						$this->data['forgot_error'] = $this->validation->_error_prefix . T_('Your account has been locked.') . $this->validation->_error_suffix;
					}
				}
				else
				{
					$this->data['forgot_error'] = $this->validation->_error_prefix . T_('Incorrect login.') . $this->validation->_error_suffix;
				}
			}
			else
			{
				$this->data['forgot_error'] = $this->validation->error_string;
			}
		}

		$this->data['login_error'] = '';
		$this->layout 	= 'page';
		$this->view 	= $this->curl . '/login';
		//pr($this->data);
		$this->renderLayout();
	}

	function reset_password($code = null)
	{
		if (!empty($code))
		{
			if ($this->user_model->resetPasswordUser($code) || $this->company_model->resetPasswordUser($code))
			{
				$this->log->writeMessage('done', T_('Your password has changed. You may entering system using your login and new password from email.'));

				redirect('/');
			}
			else
			{
				$this->log->writeMessage('error', T_('The password did not saved.'));
				redirect('/');
			}
		}

		$this->data['Title'] = '����� ������';

		$this->renderLayout();
	}

	function logout()
	{
		$this->auth->logout();

		redirect('/');
	}

	function details()
	{
		$id = $this->auth->getID();

		if (empty($id))
		{
			/*$this->view = '_elements/prohibited_page';
			$this->renderLayout();
			return;*/
			return false;
		}

		if ($this->auth->getUserData('role') == USER_ROLE_CONTRIBUTOR)
		{
			$this->view 	= '/contributors/details';
			$this->data['Title'] =  T_('Edit Contributor profile information');
			$this->validation->set_fields($this->user_model->fields);
			$object = $this->user_model->get($id);

			if (!count($object))
			{
				$this->renderElement('query_no_object');
				return false;
			}

			$this->id_user = $id;
			$this->data['picture'] = $object['picture'];

			if (!count($_POST))
			{
				$this->validation->id 				= $object['id'];
				$this->validation->first_name 		= $object['first_name'];
				$this->validation->last_name 		= $object['last_name'];
				$this->validation->middle_initial 	= $object['middle_initial'];
				$this->validation->maiden_name 		= $object['maiden_name'];
				$this->validation->social_security_number = $object['social_security_number'];
				$this->validation->email 			= $object['email'];
				$this->validation->city 			= $object['city'];
				$this->validation->id_geo_states	= $object['id_geo_states'];
				//$this->validation->type_hear	 	= $object['type_hear'];
				$this->validation->address 			= $object['address'];
				$this->validation->status 			= $object['status'];
				$this->validation->balance 			= $object['balance'];
				$this->validation->apt 				= $object['apt'];
				$this->validation->zip 				= $object['zip'];
				$this->validation->phone 			= $object['phone'];
				$this->validation->company 			= $object['company'];
				$this->validation->position 		= $object['position'];
				$this->validation->education 		= $object['education'];
				$this->validation->biography 		= $object['biography'];

				if (!empty($object['birthday']))
				{
					$arr = explode(' ', $object['birthday']);
					$arr = explode('-', $arr[0]);
					$this->data['year']  = ($arr[0][0] == '0') ? substr($arr[0], 1) : $arr[0];
					$this->data['month'] = ($arr[1][0] == '0') ? substr($arr[1], 1) : $arr[1];
					$this->data['day']   = ($arr[2][0] == '0') ? substr($arr[2], 1) : $arr[2];
				}
			}
			else
			{
				$rules = array('first_name', 'last_name', 'middle_initial', 'maiden_name', 'social_security_number', 'email', 'city', 'id_geo_states', 'address', 'apt', 'zip', 'new_password', 'password_confirm', 'company', 'position', 'education', 'biography');
				$this->validation->set_rules($this->user_model->getRules($rules));

				$this->validation->set_message('__loginFree', '<span class="black bold">�'.T_("Contributor").'�</span> '.T_("already exists with such email. Please change the email."));

				if ($this->validation->run() === TRUE)
				{
					$item = array();
				 	$item['id'] 			= $this->validation->id;
			        $item['first_name']     = $this->validation->first_name;
			        $item['last_name']     	= $this->validation->last_name;
			        $item['middle_initial'] = $this->validation->middle_initial;
			        $item['maiden_name']    = $this->validation->maiden_name;
			        $item['social_security_number'] = $this->validation->social_security_number;
			        $item['email']     		= $this->validation->email;
			        $item['city']     		= $this->validation->city;
			        $item['id_geo_states']  = $this->validation->id_geo_states;
			        $item['address']     	= $this->validation->address;
			        $item['apt']     		= $this->validation->apt;
			        $item['zip']      		= $this->validation->zip;
			        $item['company']  		= $this->validation->company;
			        $item['position']  		= $this->validation->position;
			        $item['education'] 		= $this->validation->education;
			        $item['biography'] 		= $this->validation->biography;

			        $day 	= $this->input->post('day');
					$month 	= $this->input->post('month');
					$year 	= $this->input->post('year');
					if ( !empty($day) && !empty($month) && !empty($year) )
					{
						$item['birthday'] 	= $year . '-' . $month  . '-' . $day;
					}

					if (!empty($this->validation->password))
					{
						$item['password'] 	= $this->validation->password;
					}

					$this->user_model->update($item);

					// Upload Profile Picture
					$config['upload_path'] = '../files/temp/';
					$config['allowed_types'] = 'jpg|jpeg|png|gif';
					$config['max_size']	= '2048';

					$this->load->library('upload', $config);

					if (!empty($_FILES['imagefile']['name']))
					{
						if ( $this->upload->do_upload('imagefile'))
						{
							$this->file = $this->upload->data();

							// Create Picture Miniatures
							$schemes = array('120x100' => array( // Site / Contributor / Profile / Small
														'width' => 120,
														'height' => 100
														));
							$settings = $this->config->item('thumb_settings');
							$settings['file_sizetype'] = '120x100';
							$this->_createThumbnail($schemes, $settings);
						}
					}

					redirect('/user/details/');
				}
			}
		}
		else if ($this->auth->getUserData('role') == USER_ROLE_COMPANY)
		{
			$this->view 	= '/companies/details';
			$this->data['Title'] =  T_('Edit Company profile information');
			$this->validation->set_fields($this->company_model->fields);
			$object = $this->company_model->get($id);
			//pr($object);
			if (!count($object))
			{
				$this->renderElement('query_no_object');
				return false;
			}

			$this->id_user = $id;

			if (!count($_POST))
			{
				$this->validation->id 				= $object['id'];
				$this->validation->first_name 		= $object['first_name'];
				$this->validation->last_name 		= $object['last_name'];
				$this->validation->email 			= $object['email'];
				$this->validation->city 			= $object['city'];
				$this->validation->id_geo_states	= $object['id_geo_states'];
				//$this->validation->type_hear	 	= $object['type_hear'];
				$this->validation->street 			= $object['street'];
				$this->validation->status 			= $object['status'];
				$this->validation->zip 				= $object['zip'];
				$this->validation->phone 			= $object['phone'];
				$this->validation->name 			= $object['name'];
				$this->validation->website 			= $object['website'];
				$this->validation->id_industries 	= $object['id_industry'];

				if (!empty($object['birthday']))
				{
					$arr = explode(' ', $object['birthday']);
					$arr = explode('-', $arr[0]);
					$this->data['year']  = ($arr[0][0] == '0') ? substr($arr[0], 1) : $arr[0];
					$this->data['month'] = ($arr[1][0] == '0') ? substr($arr[1], 1) : $arr[1];
					$this->data['day']   = ($arr[2][0] == '0') ? substr($arr[2], 1) : $arr[2];
				}
			}
			else
			{
				$rules = array('first_name', 'last_name', 'name', 'email', 'new_password', 'password_confirm', 'id_industries', 'job', 'employees', 'street', 'city', /*'id_geo_states',*/ 'zip', 'phone', 'website');
				//$rules = array('first_name', 'last_name', 'middle_initial', 'maiden_name', 'social_security_number', 'email', 'city', 'id_geo_states', 'address', 'apt', 'zip', 'new_password', 'password_confirm', 'company', 'position', 'education', 'biography');
				$this->validation->set_rules($this->company_model->getRules($rules));

				$this->validation->set_message('__loginFree', '<span class="black bold">�'.T_("Contributor").'�</span> '.T_("already exists with such email. Please change the email."));

				if ($this->validation->run() === TRUE)
				{
					$item = array();
				 	$item['id'] 			= $this->validation->id;
			        $item['first_name']     = $this->validation->first_name;
			        $item['last_name']     	= $this->validation->last_name;
			        $item['name']  			= $this->validation->name;
			        $item['job'] 			= $this->validation->job;
			        $item['email']     		= $this->validation->email;
			        $item['city']     		= $this->validation->city;
			        $item['id_geo_states']  = $this->validation->id_geo_states;
			        $item['street']     	= $this->validation->street;
			        $item['website']     	= $this->validation->website;
			        $item['phone'] 			= $this->validation->phone;
			        $item['zip']      		= $this->validation->zip;

			        $day 	= $this->input->post('day');
					$month 	= $this->input->post('month');
					$year 	= $this->input->post('year');
					if ( !empty($day) && !empty($month) && !empty($year) )
					{
						//$item['birthday'] 	= $year . '-' . $month  . '-' . $day;
					}

					if (!empty($this->validation->password))
					{
						$item['password'] 	= $this->validation->password;
					}

					$this->company_model->update($item);

					//redirect('/');
				}
			}
		}

		$this->renderLayout();
	}


	function credit_cards()
	{
		$id = $this->auth->getID();

		if (!empty($id))
		{

		}

		$this->data['Title'] =  T_('Credit Cards');
		$this->view = $this->curl.'/credit_cards';
		$this->renderLayout();
	}

	function upgrade()
	{
		$id = $this->auth->getID();

		if (!empty($id))
		{

		}

		$this->data['Title'] =  T_('Upgrade or downgrade account');
		$this->view = $this->curl.'/upgrade';
		$this->renderLayout();
	}

	function __loginFree($email)
	{
		return $this->user_model->loginFree($email);
	}

	function __correct_pass($password)
	{
		
		return $this->user_model->correct_pass($password);
	}
	
	
	
  function __phoneFree()
  {
    if (!empty($this->data['ani']))
    {
        foreach ($this->data['ani'] as $phone)
        {
            $res = $this->user_model->phoneFree($phone);
            if (!$res)
            {
                $this->validation->set_message('__phoneFree', '��������� <span class="black bold">������ ��������</span> ��� ����� � ����');
                return false;
            }
        }

        return true;
    }
    else
    {
        $this->validation->set_message('__phoneNumber', '���������� �������� <span class="black bold">������ ��������</span>');
        return false;
    }
  }

  function __phoneValid()
  {
  	/*echo "Ffffffffff";*/
  	return false;/*
    if (!empty($this->data['ani']))
    {
        foreach ($this->data['ani'] as $phone)
        {
            if (!preg_match( '/^[\-+]?[0-9]*\.?[0-9]+$/', $phone))
            {
            	echo $phone;
            	$this->validation->set_message('__phoneValid', '�������� ������ ���� <span class="black bold">������ ��������</span>. ���������� ������� - ������ �����.');
            	return false;
            }
        }

        return true;
    }*/
  }

	function __captcha($string)
	{
	   $session_id = set_value('captcha_id', 0);
	   if ($this->captcha_model->check($session_id, $string) === false)
	   {
	      return false;
	   }

	   return true;
	}

	function __agree($checkbox)
	{
	   if ($checkbox == 1) return true;
	   else return false;
	}

	function activation($code = null)
	{
		if (!empty($code))
		{
			if ($this->user_model->activateUser($code))
			{
				$this->log->writeMessage('done', T_('Your account has activated. You may enter the system using your login and password.'));
			}
			else
			{
				$this->log->writeMessage('error', T_('Account has not activated.'));
			}

			redirect('/user/login');
		}

		$this->data['Title'] = 'Account Activation';

		$this->renderLayout();
	}

	function _createThumbnail($schemes, $settings)
	{
		if (!empty($this->file['file_name']))
		{
			$file_path = '../files/' . $settings['temp_file_dir'] . $this->file['file_name'];
			$file_gabarites = getimagesize($file_path);

			$this->db->set('picture', $this->auth->getID() . $this->file['file_ext']);
			$this->db->where('id', $this->auth->getID());
			$this->db->update('contributors');

			$settings['source_image'] = '../files/' . $settings['temp_file_dir'] . $this->file['file_name'];

			$this->load->library('image_lib', $settings);
			foreach ($schemes as $key => $scheme)
			{
				foreach ($scheme as $param => $value)
				{
					$settings[$param] = $value;
				}
				$settings['file_sizetype'] = $key;
				$settings['new_image'] = '../files/uploads/photo/profiles/contributors/' . $this->auth->getID() . $this->file['file_ext'];
				$settings['create_thumb'] = false;
				$settings['maintain_ratio'] = true;

				//pr($settings);
				$this->image_lib->initialize($settings);
				@mkdir('../files/uploads/photo/profiles/', DIR_WRITE_MODE);
				@mkdir('../files/uploads/photo/profiles/contributors/', DIR_WRITE_MODE);

				//if ( $this->image_lib->image_process_gd_add_background('resize', $settings['width'], $settings['height']))
				if ( $this->image_lib->resize())
				{
					//echo "1";
					copy($settings['source_image'], $settings['new_image']);

				}
				else
				{
					//echo "2";
    				echo $this->image_lib->display_errors();

				}
				
			}
			@unlink($settings['source_image']);
		}
	}


    function profile()
    {
        $this->data['Title'] = T_('My Profile');
    	$this->data['profileblock_user_settings'] = NULL;
		$this->data['profileblock_notifications'] = NULL;
		$this->data['profileblock_user_billing_info'] = NULL;
		$this->data['profileblock_user_prof_ref'] =  NUlL;
        $this->renderLayout();
    }

    function requests()
    {
        $this->renderLayout();
    }

    function user_settings()
    {
     	 $this->renderLayout();
    }
    function notification_settings()
    {
    	
    	$this->data['profileblock_user_settings'] = NUll;
		$this->data['profileblock_notifications'] = 'bold_id';
		$this->data['profileblock_user_billing_info'] = NUll;
		$this->data['profileblock_user_prof_ref'] = NUlL;
		$this->data['Title'] = 'My Profile - Notification Settings';

        $userID = $this->auth->getID();

     	$this->user_model->getNotifications($userID);

        $this->renderLayout();

    }
    
    function referral_program()
    {
         $this->data['Title'] = T_('My Profile - Referal Program');
     	 $this->renderLayout();
    }
    function referral_requests()
    {
         $result = $this->referral_model->search();

         $this->data['referrals'] = $result;
         $this->data['status'] = $this->config->item('request_status');
         $this->data['Title']=T_('My Referral Requests');

         $this->renderLayout();
    }
 	function contact_us()
    {
    	$this->validation->set_fields($this->contact_us_model->fields);

		if (count($_POST))
		{
			$rules = array('your_name', 'phone', 'email', 'concerning', 'preferred_contact');
			$this->validation->set_rules($this->contact_us_model->getRules($rules));

			if ($this->validation->run() === TRUE)
			{
				$arr['email_name']      = EMAIL_CONTACT;
                $arr['user_name'] 		= $this->validation->your_name;
				$arr['phone']	= $this->validation->phone;
				$arr['email']		 	= $this->validation->email;
				$concerning_config = $this->config->item('concerning');
				$arr['concerning']		= ($this->validation->concerning) ? $concerning_config[$this->validation->concerning] : '';
				$preferred_contact = $this->config->item('preferredContact');
                $arr['preferred_contact'] = $preferred_contact[$this->validation->preferred_contact];
                $arr['message'] = $this->validation->message;


                $result = sendEmail($arr);

				redirect('/');
			}
		}

		$this->data['Title'] = T_('Contact Us');

     	$this->renderLayout();
    }
    function referral_details($referral = 0){

        $result = $this->referral_model->getReferralDetails($referral);
        $this->data['message_error']    = Null;
        
        if(!empty($result)){
            $status = $this->config->item('request_status');
            $this->data['Title']               = 'Referral Details';
            $this->data['status']              = $status[$result['ur_status']];
            $this->data['member_id']           = $this->auth->getID();
            $this->data['result']              = $result;
        }else{
            $this->data['message_error']       = $this->db_error;
        }
        $this->renderLayout();
    }

	function post_request()
    {
    	$this->validation->set_fields($this->user_model->fields);

        $default_status = '1';

        $userStatus                             = $this->config->item('request_status');
        $this->data['user_member_id']           = $this->auth->getID();
        $this->data['user_referral_no']         = $this->referral_model->get_id();
        $this->data['user_status']              = $userStatus[$default_status];
        $this->data['user_date_posted']         = date('Y-m-d');
        
        if($this->input->post('postRequest'))
		{
            $rules = array('referral_abstract','referral_details','end_date','ask_price');
        	$this->validation->set_rules($this->user_model->getRules($rules));
	
			if ($this->validation->run() === TRUE)
			{
                $item['ur_user_id']          = $this->auth->getID();
                $item['ur_id']               = $this->data['user_referral_no'];
                $item['ur_status']           = $default_status;
				$item['ur_date_posted']      = $this->data['user_date_posted'];

                $item['ur_abstract']  = $this->validation->referral_abstract;
                $item['ur_details']   = $this->validation->referral_details;
                $item['ur_end_date']  = $this->validation->end_date;
                $item['ur_ask_price'] = $this->validation->ask_price;
				
                if ($this->referral_model->insert($item))
       			{
                    
					redirect('/user/referral_requests');
       			}
                
			}
		}

		$this->data['Title'] = T_('Post Referral Request');

        $this->renderLayout();

    }


	function profile_payment_info()
    {
     	$id = $this->auth->getID();
     	
     	$this->data['profileblock_user_settings'] = NULL;
		$this->data['profileblock_notifications'] = NULL;
		$this->data['profileblock_user_billing_info'] = 'bold_id';
		$this->data['profileblock_user_prof_ref'] = NUlL;
    	
		
		if (!empty($id))
		{
						
			$this->data['Title'] =  T_('My profile - Payment Information');
			$this->validation->set_fields($this->user_model->fields);

			$object = $this->user_model->get($id);
			$this->data['user_created'] = $object['user_created'];
						
			
			$this->id_user = $id;

			if (!isset($_POST['enter'])){				
				
				$this->validation->first_name 				= $object['user_first_name'];
				$this->validation->last_name 				= $object['user_last_name'];				
				$this->validation->phone					= $object['user_phone'];
				$this->validation->address					= $object['user_address'];				
				$this->validation->city 					= $object['user_city'];
				$this->validation->country_ID 				= $object['user_country'];
				$this->validation->zip_code					= $object['user_zip_code'];
				$this->validation->card_type				= $object['user_card_type'];
				$this->validation->card_number				= $object['user_card_number'];
				$this->validation->exp_month				= $object['user_exp_month'];	
				$this->validation->exp_year					= $object['user_exp_year'];	
				$this->validation->security_code			= $object['user_security_code'];
				
				if($object['user_country'] == "840"){
					$this->validation->state_ID					= $object['user_state'];	                
	            }else if($object['user_country']!=="0"){
	                $this->validation->province					= $object['user_state'];
	            }
					
						
				
			} else {
				
				if($object['user_country'] == "840"){
	                $state_province='state_ID';
	            }else if($object['user_country']!=="0"){
	                $state_province='province';
	            }
	            $rules = array('first_name', $state_province, 'last_name', 'phone', 'address', 'city', 'country_ID', 'zip_code', 'card_type', 'exp_month', 'exp_year', 'security_code');
				
				
				
				
				$this->validation->set_rules($this->user_model->getRules($rules));
								
				if ($this->validation->run() === TRUE)
				{
					$item = array();
				 	$item['user_ID'] 				= $id; 
			        $item['user_first_name']		= $this->validation->first_name; 
			        $item['user_last_name'] 		= $this->validation->last_name;
			        $item['user_phone']     		= $this->validation->phone;
			        $item['user_address']     		= $this->validation->address;
			        $item['user_state']				= $this->validation->$state_province; 
			        $item['user_city'] 				= $this->validation->city;
			        $item['user_country']     		= $this->validation->country_ID;
			        $item['user_zip_code']     		= $this->validation->zip_code;
			        $item['user_card_type']     	= $this->validation->card_type;
			        $item['user_card_number']     	= $this->validation->card_number;
			        $item['user_exp_month']     	= $this->validation->exp_month;
			        $item['user_exp_year']     		= $this->validation->exp_year;
			        $item['user_security_code']     = $this->validation->security_code;
			        
			        
			        
				
			     //   $item['user_confirm_password']	= $this->validation->password_confirm;

					
					$this->user_model->update($item);

					redirect('/user/profile_payment_info/');
				}
			}
		}else{  redirect('/user/register');  }


		$this->renderLayout();
    }
	function connect_with_bidder($referral = 0, $bid = 0)
    {
        $this->validation->set_fields($this->user_model->fields);

        $bidInfo = $this->bids_model->searchBid($bid);
        $refInfo = $this->referral_model->searchReferral($referral);
        $status = $this->config->item('request_status');
        $this->data['message_error']   = Null;

        if(!empty($bidInfo)&&!empty($refInfo)){
                $this->data['Title']              = T_('Connect with Bidder');
                $this->data['sender_id']          = $this->auth->getID();
                $this->data['status']             = $status[$refInfo['ur_status']];
                $this->data['referral_no']        = $refInfo['ur_id'];
                $this->data['date_posted']        = $refInfo['ur_date_posted'];
                $this->data['referral_abstract']  = $refInfo['ur_abstract'];
                $this->data['ask_price']          = $refInfo['ur_ask_price'];
                $this->data['bid_price']          = $bidInfo['ub_price'];
                $this->data['receiver_id']        = $bidInfo['ub_user_ID'];
                $this->data['bid_id']        	  = $bidInfo['ub_ID'];

                if (count($_POST))
                {
                    $rules = array('message_header','message_text');
                    $this->validation->set_rules($this->user_model->getRules($rules));

                    if ($this->validation->run() === TRUE)
                    {
                        $item['inbox_message_header']   = $this->validation->message_header;
                        $item['inbox_message_text']     = $this->validation->message_text;

                        $item['inbox_user_ID']		  = $bidInfo['ub_ID'];
                        $item['inbox_date_posted']	  = $refInfo['ur_date_posted'];
                        $item['inbox_status'] 		  = $refInfo['ur_status'];
                        $item['inbox_sender']			  = $this->data['sender_id'];
                        $item['inbox_referral_no']	  = $refInfo['ur_id'];
                        $item['inbox_ask_price']		  = $refInfo['ur_ask_price'];
                        $item['inbox_bid_price']		  = $bidInfo['ub_price'];

                        if ($this->inbox_model->insert($item)) {

                            redirect('/user/profile');
                        }

                    }

                    $this->view = '/user/connect_with_bidder';
                }
        }else{
            $this->data['message_error']   = $this->db_error;
        }
        $this->renderLayout();

    }
	function accept_bid($referral=0,$bid=0)
    {
     	 $this->validation->set_fields($this->user_model->fields);
         $bidInfo = $this->bids_model->searchBid($bid);
         $refInfo = $this->referral_model->searchReferral($referral);
         $status = $this->config->item('request_status');
        $this->data['message_error']            = Null;
        if(!empty($refInfo)&&!empty($bidInfo)){
            $this->data['Title']                = T_('Accept Bid');
            $this->data['member_id']            = $this->auth->getID();
            $this->data['referral_no']          = $refInfo['ur_id'];
            $this->data['referral_abstract']    = $refInfo['ur_abstract'];
            $this->data['status']               = $status[$refInfo['ur_status']];//"Accepter"?
            $this->data['date_posted']          = $refInfo['ur_date_posted'];

            $this->data['bid_id']               = $bidInfo['ub_ID'];
            $this->data['bidder_id']            = $bidInfo['ub_user_ID'];
            $this->data['accepted_bid']         = $bidInfo['ub_price'];

            if (count($_POST))
            {
                $condition = "AND ur_id='".$referral."'";
                $this->referral_model->changeField("ur_status",'4',$condition);//"Paid"?
                redirect('/user/profile');
            }
        }else{
            $this->data['message_error']            = $this->db_error;
        }

        $this->renderLayout();
    }

	function bids($referral = 0)
    {
         $status = $this->config->item('request_status');
         $this->data['bids'] = $this->bids_model->getByReferral($referral);
         $this->data['bids_number'] = $this->bids_model->countBids($referral);
         $this->data['Title'] = T_('Referral');

         $refInfo = $this->referral_model->searchReferral($referral);
         $this->data['message_error']   = Null;
        if(!empty($refInfo)){
            $this->data['ref_id']           = $refInfo['ur_id'];
            $this->data['ref_status']       = $status[$refInfo['ur_status']];
            $this->data['ref_date_posted']  = $refInfo['ur_date_posted'];
            $this->data['ref_end_date']     = $refInfo['ur_end_date'];
            $this->data['ref_abstract']     = $refInfo['ur_abstract'];
            $this->data['ref_ask']          = $refInfo['ur_ask_price'];
            $this->data['ref_bids']         = $refInfo['ur_bid_num'];
            $this->data['ref_avg_bid']      = $refInfo['ur_bid_avg'];
         }else{
             
             $this->data['message_error']   = $this->db_error;
         }
     $this->renderLayout();
    }
      function bidoptions($referral = 0,$bid = 0)
    {
        $status = $this->config->item('request_status');
        $postscript = array(
                            '1' => 'This bid is still Open since you have not connected with the Bidder. Once you have connected satisfactorily then the status will change to Connected and at that point you can either Accept the bid or Connect with another Bidder.',
                            '2' => 'This bid was closed.',
                            '3' => 'You can accept this bid, as you connected with bidder.',
                            '4' => 'This bid is paid.',
                            '5' => 'Waiting for desicion.',
                            '6' => 'This bid was successfuly carried out.',
                            );

        $bidInfo = $this->bids_model->searchBid($bid);
        $refInfo = $this->referral_model->searchReferral($referral);

        if(!empty($bidInfo)&&!empty($refInfo)){
            $this->data['Title']            = T_('Referral');
            $this->data['Title2']           = T_('Bid');
            $this->data['bidInfo']          = $bidInfo;
            $this->data['refInfo']          = $refInfo;
            $this->data['status']           = $status[$refInfo['ur_status']];
            $this->data['postscript']       = $postscript[$refInfo['ur_status']];

            $this->data['ub_ur_connection'] = $bidInfo['ub_ur_connection'];//trash
        
        }else{
            $this->data['message_error']   = $this->db_error;
        }
        $this->renderLayout();
    }
    
	function message_inbox()
	{
    	
    	$this->renderLayout();
    }

    function user_profile()
    {
		$id = $this->auth->getID();
		if (!empty($id))
		{
			$this->validation->set_fields($this->user_model->fields);
			$object = $this->user_model->get($id);
			$this->id_user = $id;

            	
			if (!isset($_POST['enter']))
			{
                $this->validation->id 						= $id;
				$this->validation->first_name 				= $object['user_first_name'];
				$this->validation->last_name 				= $object['user_last_name'];
				$this->validation->email 					= $object['user_email'];
                $this->data['Title']                        =T_('My Profile - User Settings');
			}
			else
			{
				
				$rules = array('first_name', 'last_name', 'email', 'new_password', 'password_confirm');
				$this->validation->set_rules($this->user_model->getRules($rules));
				
				
				$this->validation->set_message('__loginFree', '<span class="black bold">'.T_("User").'</span> '.T_("already exists with such email. Please change the email."));
				$this->validation->set_message('__correct_pass', T_("Password lenght must consist ot both letters and numbers with at least 1 capital letter"));				
				
				if ($this->validation->run() === TRUE)
				{
					$item = array();
				 	$item['user_ID'] 				= $object['user_ID'];
			        $item['user_first_name']		= $this->validation->first_name; 
			        $item['user_last_name'] 		= $this->validation->last_name;
			        $item['user_email']     		= $this->validation->email;
			        $item['user_password']     		= $this->validation->new_password;
			     //   $item['user_confirm_password']	= $this->validation->password_confirm;
					
					$this->user_model->update($item);

					redirect('/user/profile/');
				}
			}
		}

		$this->data['Title'] =  T_('My Profile - User Settings');

		$this->data['profileblock_user_settings'] = 'bold_id';
		$this->data['profileblock_notifications'] = NUll;
		$this->data['profileblock_user_billing_info'] = NUll;
		$this->data['profileblock_user_prof_ref'] = NUlL;
		
		$this->renderLayout();
    }

	function profile_referral(){ 
		$user_name = $this->auth->getUserData('user_first_name');              
        $this->validation->set_fields($this->user_model->fields);

        $this->data['Title'] = 'My Profile - Referral Program';
        $this->data['profileblock_user_settings'] = NULL;
		$this->data['profileblock_notifications'] = NULL;
		$this->data['profileblock_user_billing_info'] = NULL;
		$this->data['profileblock_user_prof_ref'] = 'bold_id';
               
		$rules = array('full_name', 'friendemail');
		$this->validation->set_rules($this->user_model->getRules($rules));	

		  if (isset($_POST['sendToFriend'])){

        		$data_friend['uf_id'] = $this->friends_model->get_id();
                $data_friend['uf_full_name'] = $this->validation->full_name;
                $data_friend['uf_email'] = $this->validation->friendemail;
                $data_friend['uf_activation_code'] = generatecode();
                $data_friend['uf_user_ID'] = $this->auth->getID();
                $data_friend['uf_status']  = "2";
                
                $this->friends_model->insert($data_friend);

                $user_names     = $this->user_model->getUserField('user_first_name, user_last_name');
                $link = $this->config->item('site_url') . $this->config->item('base_url') .'user/register/?fr_code='.$data_friend['uf_activation_code'];

                $friend['email_name']        = EMAIL_REGISTER_GUEST;
                $friend['email']             =  $this->validation->friendemail;
                $friend['activation_link']   = '<a href="'.$link.'">'.$link.'</a>';
                $friend['user_full_name']    =  $user_names['user_first_name'].' '.$user_names['user_last_name'];
                $friend['uf_full_name']      = $this->validation->full_name;

                $result = sendEmail($friend);
				
                redirect('/user/profile');
            }
				$this->renderLayout();
		
        }

   function test(){
    $CI =& get_instance();
	$CI->load->library('email');


	$subject = "Subject";

    $message = "message";

    $config['mailtype'] = 'html';
    $config['protocol'] = 'smtp';
    $config['smtp_host'] = 'mail.mirotel.net';
    $config['smtp_user'] = 'relay@l7hosting.in';
    $config['smtp_pass'] = '%relay2011';

    $config['charset'] = 'utf-8';
	$config['newline'] = '\r\n';


	$CI->email->initialize($config);
	$CI->email->from("fk@mi.com", "some");
	$CI->email->to("donebes@gmail.com");
	$CI->email->subject($subject);
	$CI->email->message($message);
	$CI->email->send();

        }
}